package cn.mes.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@RestController
@Controller
public class RouterController {

    /**
     * 非法路由拦截
     *
     * @return
     * @throws IOException
     */

    @GetMapping(value = "/{html}")
    public ResponseEntity<InputStreamResource> index(
            @PathVariable("html") String html,
            HttpServletRequest request) throws IOException {
        // 确保HTML文件名安全，防止路径遍历攻击
        String safeHtmlName = html.replaceAll("[^a-zA-Z0-9_-]", "");
        // 使用类加载器获取资源，更可靠的方式
        InputStream inputStream = getClass().getResourceAsStream("/html/" + safeHtmlName + ".html");
        if (inputStream == null) {
            throw new FileNotFoundException("资源不存在: " + safeHtmlName + ".html");
        }
        try {
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_HTML);
            // 可以添加缓存控制头
            headers.setCacheControl(CacheControl.noCache().getHeaderValue());
            return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
        } catch (Exception e) {
            // 确保输入流在异常情况下被关闭
            inputStream.close();
            throw new IOException("处理资源时发生错误: " + safeHtmlName + ".html", e);
        }
    }


}
